package org.upt.dcda;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.jboss.resteasy.logging.Logger;
import org.upt.dcda.db.BookEntity;
import org.upt.dcda.exceptions.BookstoreException;

/**
 * Session Bean implementation class SearchManagerBean
 */
@Stateless
@LocalBean
public class SearchManagerBean implements SearchManagerBeanRemote,
		SearchManagerBeanLocal
{
	protected final Logger	logger	= Logger.getLogger(this.getClass());

	@PersistenceContext
	private EntityManager	entityManager;

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<BookEntity> browse(String... tags) throws BookstoreException
	{
		try
		{
			final Collection<String> tagCollection = new ArrayList<String>(
					tags.length);

			for (String tag : tags)
			{
				tagCollection.add(tag);
			}

			TypedQuery<BookEntity> query = entityManager.createNamedQuery(
					BookEntity.GET_BOOKS_BY_TAGS_QUERY, BookEntity.class);

			query.setParameter("tags", tagCollection);

			return query.getResultList();
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<BookEntity> search(String key) throws BookstoreException
	{

		try
		{
			logger.info("search(key = " + key);

			TypedQuery<BookEntity> query = entityManager.createNamedQuery(
					BookEntity.SEARCH_BY_BOOK_TITLE, BookEntity.class);

			query.setParameter("key", key);

			return query.getResultList();
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<BookEntity> makeRecommandations(int userId)
			throws BookstoreException
	{
		return new ArrayList<BookEntity>(); // FIXME
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<BookEntity> browseAll() throws BookstoreException
	{
		try
		{
			TypedQuery<BookEntity> query = entityManager.createNamedQuery(
					BookEntity.GET_ALL_BOOKS_QUERY, BookEntity.class);

			return query.getResultList();
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

}
